import http from "./request";

http.interceptor.request = (config) => {
	config.headers = {
		"Content-Type": "application/json",
		charset: "UTF-8",
		"X-Requested-With": "XMLHttpRequest",
	};
};

http.interceptor.response = (response) => {
	const data = response.data;
	uni.hideLoading();
	if (response.statusCode === 422) {
		uni.showToast({
			title: response.data.message,
			icon: "none",
		});
		return new Promise(() => {});
	}

	if (response.statusCode === 500) {
		return new Promise(() => {});
	}

	switch (data.code) {
		case 200:
			return data.data;
		case -2: {
			uni.showModal({
				title: data.message,
				showCancel: false
			});
			return Promise.reject(data.message);
		}
		case 1: {
			return data.data || data.message?.data || data.message;
		}
		case -1: {
			uni.showModal({
				title: data.msg,
				showCancel: false,
			});
			return null;
		}
		case 100000: {
			if (data.msg === '无效请求') {
				uni.showModal({
					title: '验证码已过期，请重新扫码',
					showCancel: false,
				});
				return Promise.reject(data.msg);
			}
			uni.showModal({
				title: data.msg,
				showCancel: false,
			});
			return Promise.reject(data.msg);
		}
		case 0: {
			uni.hideLoading();
			return data.data;
		}
		case 401: {
			return new Promise(() => {});
		}
		default: {
			return data.data;
		}
	}
	return response;
};

export default http;